// pages/pay/pay.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
      takeType:0,
      orderInfo:{},
      shopInfo:{}, //店铺信息
      consigneeInfo:{}, //收货人信息
      paymentType:"weixin",
      from:"routine",
      goods:[],
      totalPayPrice:0,
      realPayPrice:0,
      remark:"订单备注"
  },
  onPaymentMethodChange(event) {
    console.log(event.detail.value)
    this.setData({
      paymentType: event.detail.value,
    });
  },
   goPay(){
    app.wxRequest('POST', '/order/create', this.data, (res) => {
      if (200 == res.code) {
        
        console.log("订单创建成功")
        if('weixin'===this.data.paymentType){
          this.initiatePayment(res.data)
        }
        app.clearCart()
        app.showMsg(res.data.payMsg)
      }else{
        app.showMsg(res.msg);
      }
    }, (err) => {
        app.showMsg(err.errMsg);
      console.log("订单创建失败")
      console.log(err.errMsg)
    })
    wx.switchTab({
      url: '/pages/order/order'
    })
  },
  initiatePayment(data){
    console.log(data)
    wx.requestPayment({
      timeStamp: this.data.payParam.timeStamp,
      nonceStr: this.data.payParam.nonceStr,
      package: this.data.payParam.package,
      signType: 'MD5',
      paySign: this.data.payParam.paySign,
      success: res => {
        this.setData({
          payResult: '支付成功'
        });
      },
      fail: error => {
        this.setData({
          payResult: '支付失败'
        });
        console.log(error);
      }
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log("onLoad")
    this.getTotalPrice()
  },
  getTotalPrice(){
   const cartList= wx.getStorageSync('cartList')
    let totalPrice=0;
    cartList.forEach(good=>{
      totalPrice+=good.spuSellPrice
    }) 
    this.setData({
      realPayPrice:totalPrice,
      goods:cartList
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    console.log("onReady")
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    console.log("onShow")
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})